package com.kelly.kellymusicplayer.tools;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

import com.kelly.kellymusicplayer.entity.MusicInfo;
import com.kelly.kellymusicplayer.listener.OnPlayerStartListener;
import com.kelly.kellymusicplayer.listener.OnProgressListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by kelly on 2015/12/22.
 */
public class MusicPlayManager {

    private static final int PLAYMODE_RECIRCLE_ALL = 1;
    private static final int PLAYMODE_SINGLE = 2;
    private static int PLAY_MODE = PLAYMODE_RECIRCLE_ALL;

    private static MusicPlayManager musicPlayManager;
    private MediaPlayer mMediaPlayer;
    private Context mContext;
    private List<MusicInfo> musicInfoList = new ArrayList<>();
    private MusicInfo currentPlayMusicInfo;
    private int playPositionInMusicList;
    private int currentPosition;
    private List<OnProgressListener> onProgressListenerList = new ArrayList<>();
    private List<OnPlayerStartListener> onPlayerStartListenerList = new ArrayList<>();


    private MusicPlayManager() {
    }

    private MusicPlayManager(Context mContext) {
        this.mContext = mContext;
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                switch (PLAY_MODE) {
                    case PLAYMODE_RECIRCLE_ALL:
                        playNextMusic();
                        break;
                    case PLAYMODE_SINGLE:
                        rePlayCurrentMusicInfo();
                        break;
                }
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (mMediaPlayer.getDuration() != 0) {
                        currentPosition = mMediaPlayer.getCurrentPosition();
                        for (OnProgressListener listener : onProgressListenerList) {
                            listener.getProgress(currentPosition * 1000 / mMediaPlayer.getDuration());
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mMediaPlayer.start();
                for (OnPlayerStartListener listener : onPlayerStartListenerList) {
                    listener.onPlayerStart();
                }
            }
        });
    }

    private void rePlayCurrentMusicInfo() {
        try {
            mMediaPlayer.setDataSource(mContext, Uri.parse(currentPlayMusicInfo.getUrl()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int getDuration() {
        return mMediaPlayer.getDuration();
    }

    public static MusicPlayManager getInstance(Context context) {
        if (musicPlayManager == null) {
            musicPlayManager = new MusicPlayManager(context);
        }
        return musicPlayManager;
    }

    public void playMusicList(int position) {
        try {
            playPositionInMusicList = position;
            if (musicInfoList != null && musicInfoList.get(playPositionInMusicList) != null) {
                currentPlayMusicInfo = musicInfoList.get(playPositionInMusicList);
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(currentPlayMusicInfo.getUrl());
                mMediaPlayer.prepare();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void playNextMusic() {
        try {
            currentPlayMusicInfo = getNextMusicInfo();
//            mMediaPlayer.setDataSource(mContext, Uri.parse(currentPlayMusicInfo.getUrl()));
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(currentPlayMusicInfo.getUrl());
            mMediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void playPreviousMusic() {
        try {
            currentPlayMusicInfo = getPreviousMusicInfo();
//            mMediaPlayer.setDataSource(mContext, Uri.parse(currentPlayMusicInfo.getUrl()));
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(currentPlayMusicInfo.getUrl());
            mMediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isPlaying() {
        return mMediaPlayer.isPlaying();
    }

    public void stop() {
        if (mMediaPlayer == null)
            return;
        mMediaPlayer.stop();
        mMediaPlayer.release();
    }

    public void pause() {
        if (mMediaPlayer == null && mMediaPlayer.isPlaying())
            return;
        mMediaPlayer.pause();
    }

    public void seekTo(int position) {
        if (mMediaPlayer != null && musicInfoList != null)
            mMediaPlayer.seekTo(position);

    }

    public void resume() {
        if (mMediaPlayer == null && !mMediaPlayer.isPlaying())
            return;
        mMediaPlayer.start();
    }

    private MusicInfo getNextMusicInfo() throws Exception {
        playPositionInMusicList++;
        if (musicInfoList != null && musicInfoList.size() > playPositionInMusicList && musicInfoList.get(playPositionInMusicList) != null) {
        } else if (musicInfoList != null) {
            playPositionInMusicList = 0;
        } else {
            throw new Exception("没有下一曲");
        }
        return musicInfoList.get(playPositionInMusicList);
    }

    private MusicInfo getPreviousMusicInfo() throws Exception {
        --playPositionInMusicList;
        if (musicInfoList != null && playPositionInMusicList > 0 && musicInfoList.size() > playPositionInMusicList && musicInfoList.get(playPositionInMusicList) != null) {
        } else if (musicInfoList != null) {
            playPositionInMusicList = musicInfoList.size() - 1;
        } else {
            throw new Exception("没有上一曲");

        }
        return musicInfoList.get(playPositionInMusicList);
    }

    public List<MusicInfo> getMusicInfoList() {
        return musicInfoList;
    }

    public void setMusicInfoList(List<MusicInfo> musicInfoList) {
        this.musicInfoList = musicInfoList;
    }

    public void setProgressListener(OnProgressListener progressListener) {
        if (onProgressListenerList != null && progressListener != null && !onProgressListenerList.contains(progressListener))
            onProgressListenerList.add(progressListener);
    }

    public void removeProgressListener(OnProgressListener progressListener) {
        if (onProgressListenerList != null && progressListener != null && onProgressListenerList.contains(progressListener))
            onProgressListenerList.remove(progressListener);
    }

    public void setOnPlayerStartListener(OnPlayerStartListener playerStartListener) {
        if (onPlayerStartListenerList != null && playerStartListener != null && !onPlayerStartListenerList.contains(playerStartListener))
            onPlayerStartListenerList.add(playerStartListener);
    }

    public void removeOnPlayerStartListener(OnPlayerStartListener playerStartListener) {
        if (onPlayerStartListenerList != null && playerStartListener != null && onPlayerStartListenerList.contains(playerStartListener))
            onPlayerStartListenerList.remove(playerStartListener);
    }
}
